package linter.service.impl;

// import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import linter.POJO.DO.ModelDataDispose;
import linter.mapper.ModelDataDisposeMapper;
import linter.service.ModelDataDisposeService;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Date;

import static linter.custom.Constant.*;
import static linter.custom.CustomResultType.*;
import static linter.utils.ModelUtils.generateUUID;

/**
* @author 北煜
* @description 针对表【model_data_dispose】的数据库操作Service实现
* @createDate 2024-04-17 12:40:42
*/
@Service
public class ModelDataDisposeServiceImpl extends ServiceImpl<ModelDataDisposeMapper, ModelDataDispose>
    implements ModelDataDisposeService{

    @Resource
    ModelDataDisposeMapper modelDataDisposeMapper;

    @Override
    public String uploadModelDataDispose(MultipartFile file, String dataName, Long uuid) {
        ModelDataDispose modelDataDispose = new ModelDataDispose();
        Date date = new Date();
        //构造一个带指定Region对象的配置类
        Configuration cfg = new Configuration(Region.region2());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(ACCESS_KEY_QINIU, SECRET_KEY_QINIU);
        String bucketName = BUCKET_NAME_QINIU;
        String key = "User/DataModel/" + generateUUID() + "_" + dataName;
        String baseUrl = "http://qiniuyun.linter.top";
        String url = baseUrl + "/" + key;
        byte[] fileContent;
        try {
            fileContent = file.getBytes();
            try (ByteArrayInputStream inputStream = new ByteArrayInputStream(fileContent)) {
                String upToken = auth.uploadToken(bucketName);
                Response response = uploadManager.put(inputStream, key, upToken, null, null);
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

                modelDataDispose.setUuid(uuid);
                modelDataDispose.setDataName(dataName);
                modelDataDispose.setDataUploadUrl(url);
                modelDataDispose.setUpdateTime(date);
                modelDataDispose.setCreateTime(date);
                int flag = modelDataDisposeMapper.insert(modelDataDispose);
                String res;
                if (flag != 1) { res = SAVE_NOT_ERROR; }
                res = SAVE_SUCCESS;
                if (response.statusCode == RES_SUCCESS){
                    return res + putRet.hash + ": " + UPLOAD_SUCCESS;
                }
                throw new RuntimeException(UPLOAD_ERROR + ": " + response.bodyString());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Object dispose(Long uuid, String dataName, Integer disposeType, Integer nNeighbors) {
        // Date date = new Date();
        // ModelDataDispose modelDataDispose = new ModelDataDispose();
        RestTemplate restTemplate = new RestTemplate();
        // QueryWrapper<ModelDataDispose> queryWrapper = new QueryWrapper<>();
        String dataUrl = modelDataDisposeMapper.selUrl(uuid, dataName);
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("data_url", dataUrl);
        params.add("data_name", dataName);
        params.add("dispose_type", disposeType);
        if (nNeighbors == null){ nNeighbors = 5; }
        params.add("n_neighbors", nNeighbors);
        ResponseEntity<String> response = restTemplate.postForEntity(
                "http://127.0.0.1:5000/DataDispose", params, String.class);

        if (response.getStatusCode().is2xxSuccessful()) {
            String result = response.getBody();
            System.out.println("result: ");
            System.out.println(result);
            // 处理结果
            String main = restTemplate.postForObject(
                    "http://127.0.0.1:5000/DataDisposeMain", null ,String.class);
            if (response.getStatusCode().is2xxSuccessful()) {
                // 请求成功
                System.out.println(main);
                // 处理结果
                return "请求失败";
            }
        }
        return "请求失败";
    }
}




